/**
 * weapp-js v2.2.3(2022-4-26)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2022 Motigo, Inc.
 * 
 */
import ConsoleLog from './log.js';
import RequestCache from './request_cache.js';

class Request {
    constructor() {
        this.HOST = '';
        this.appid = '';
        this.userOpenid = '';
        this.userUnionid = '';
        this.sessionId = '';
        this.headers = {};
        this.timeout = 5000;
    }
    init(sessionId, appid, unionid, openid) {
        // init接口留着是兼容：之前的设计
        this.updateSession(sessionId, appid, openid, unionid);
    }
    setHost(host) {
        this.HOST = host;
    }
    setHeaders(headers) {
        /*
            设置自定义请求头
         */
        if (headers && typeof headers == 'object') {
            this.headers = Object.assign(this.headers, headers);
        }
    }
    setTimeout(timeout) {
        if (typeof timeout === 'number' && timeout > 0) {
            this.timeout = timeout;
        } else {
            console.error('请设置正确的timeout数值');
        }
    }
    // 禁用缓存：主要用于dev模式，外部统一禁用
    disableCache() {
        RequestCache.disable();
    }
    get(path, params, enableCache, expireIn) {
        return new Promise((resolve, reject) => {
            RequestCache.get(path, params, enableCache).then(
                data => {
                    resolve(data);
                },
                () => {
                    this.request('GET', path, params).then(
                        data => {
                            resolve(data);
                            if (enableCache === true || expireIn) {
                                RequestCache.set(path, params, expireIn, data);
                            }
                        },
                        err => {
                            reject(err);
                        }
                    );
                }
            );
        });
    }
    post(path, params) {
        return this.request('POST', path, params);
    }
    put(path, params) {
        return this.request('PUT', path, params);
    }
    delete(path, params) {
        return this.request('DELETE', path, params);
    }
    ensure() {
        return new Promise(resolve => {
            if (this.HOST) {
                resolve();
            } else {
                let timer = setInterval(() => {
                    if (this.HOST) {
                        clearInterval(timer);
                        resolve();
                    }
                }, 10);
            }
        });
    }
    updateSession(sessionId, appid, openid, unionid) {
        this.sessionId = sessionId;
        this.appid = appid;
        this.userUnionid = unionid;
        this.userOpenid = openid;
    }
    request(method, path, params) {
        return new Promise((resolve, reject) => {
            this.ensure().then(() => {
                if (this.appid.length == 0) {
                    let app = wx.getAccountInfoSync();
                    this.appid = app.miniProgram.appId;
                }
                wx.request({
                    method: method,
                    timeout: this.timeout,
                    header: Object.assign(this.headers, {
                        'content-type': 'application/json',
                        appid: this.appid,
                        openid: this.userOpenid,
                        unionid: this.userUnionid,
                        session: this.sessionId
                    }),
                    url: this.HOST + path,
                    data: params,
                    success(res) {
                        if (res.data.ret == 0) {
                            resolve(res.data.data);
                        } else {
                            reject(res.data);
                        }
                    },
                    fail(err) {
                        reject({
                            msg: err.errMsg
                        });
                        ConsoleLog.error('request fail!');
                        ConsoleLog.error(err);
                    }
                });
            });
        });
    }
}

let request = new Request();
export default request;
